import 'package:cached_network_image/cached_network_image.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/fee_detail_entity.dart';
import 'package:factoryside/bean/fee_order_entity.dart';
import 'package:factoryside/bean/order_record_entity.dart';
import 'package:factoryside/generated/json/fee_detail_entity_helper.dart';
import 'package:factoryside/generated/json/order_record_entity_helper.dart';
import 'package:factoryside/home/page_order_record.dart';
import 'package:factoryside/utils/FadeRoute.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/page_photo_view.dart';
import 'package:flutter/material.dart';

import 'fee_audit_detail.dart';

//费用单详情界面
class FeeDetailPage extends StatefulWidget {
  FeeOrderEntity data;

  FeeDetailPage(this.data);

  @override
  State<StatefulWidget> createState() {
    return _FeeDetailState();
  }
}

class _FeeDetailState extends State<FeeDetailPage> {

  FeeDetailEntity feeDetailEntity;

  var workAddr;
  var userAddr;

  List tempList=[];

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getFeeInfo();
  }

  void getFeeInfo() {
    RequestUtil.post(Api.getFeeInfo, {
      'OrderID':widget.data.orderID,
      'OrderFeeApplicationID':widget.data.orderFeeApplicationID,
    }).then((value) {
      feeDetailEntity=feeDetailEntityFromJson(FeeDetailEntity(), value['Data']['data']);
      RequestUtil.post('${Api.getOrderAccessoriesRecordByGrid}',
          {'orderId': widget.data.orderID,'accessoryId':widget.data.orderFeeApplicationID,'typeId':9,'page':1, 'limit': 5}).then((value) {
        setState(() {
          List list = value['Data']['data'];
          tempList = [];
          if (list.length > 5) {
            List.generate(
                5,
                    (index) => tempList.add(orderRecordEntityFromJson(
                    OrderRecordEntity(), list[index])));
          } else {
            list.forEach((element) {
              tempList
                  .add(orderRecordEntityFromJson(OrderRecordEntity(), element));
            });
          }
        });
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          //导航栏
          title: Text(widget.data.feeNumber),
        ),
        body: feeDetailEntity!=null?Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  Container(
//                    color: Color(0xffEFEFEF),
                    child: Column(
                      children: [
                        Container(
                            color: Colors.white,
                            padding: EdgeInsets.all(10),
                            margin: EdgeInsets.only(bottom: 10),
                            child: Column(
                              crossAxisAlignment:
                              CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Expanded(
                                        child: Text('费用信息',
                                            style: TextStyle(
                                                fontWeight:
                                                FontWeight.bold))),
                                    OutlinedButton(
                                        onPressed: () {
                                          showToast('复制');
                                        },
                                        child: Text('复制',
                                            style: TextStyle(
                                                color: Colors.red)),
                                        style: ButtonStyle(
                                            side: MaterialStateProperty
                                                .all(BorderSide(
                                                color:
                                                Colors.red))))
                                  ],
                                ),
                                Divider(),
                                Row(
                                  children: [
                                    Text('审核状态：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.stateTxt}',
                                          style:
                                          TextStyle(color: Colors.grey),
                                        )),
                                  ],
                                ),
                                Row(
                                  children: [
                                    Text('费用单号：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.feeNumber}',
                                          style:
                                          TextStyle(color: Colors.grey),
                                        )),
                                  ],
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('费用类型：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.name}',
                                          style:
                                          TextStyle(color: Colors.grey),
                                        )),
                                  ],
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('申请金额：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.applicationAmount}元',
                                          style:
                                          TextStyle(color: Colors.red),
                                        )),
                                  ],
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('申请备注：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.applicationNotes}',
                                          style:
                                          TextStyle(color: Colors.grey),
                                        )),
                                  ],
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('申请时间：'),
                                    Expanded(
                                        child: Text(
                                          '${feeDetailEntity.fee.createDate}',
                                          style:
                                          TextStyle(color: Colors.grey),
                                        )),
                                  ],
                                ),
                              ],
                            )),
                        Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(10),
                          margin: EdgeInsets.only(bottom: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '凭证照片',
                                style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
                              ),
                              Divider(),
                              SizedBox(height: 10,),
                              GridView(
                                gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 5,
                                    mainAxisSpacing: 5.0,
                                    crossAxisSpacing: 5.0,
                                    childAspectRatio: 1),
                                children: List.generate(feeDetailEntity.imgs.length, (index) => buildImageItem(index)),
                                physics: NeverScrollableScrollPhysics(), //禁止滚动
                                shrinkWrap: true,
                              ),
                            ],
                          ),
                        ),
                        Container(
                            padding: EdgeInsets.all(10),
                            margin: EdgeInsets.only(bottom: 60),
                            color: Colors.white,
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text('费用单操作记录',
                                        style: TextStyle(
                                            fontWeight:
                                            FontWeight.bold)),
                                  ],
                                ),
                                Divider(),
                                GestureDetector(
                                  onTap: () {
                                    push(
                                        context,
                                        OrderRecordPage(
                                            widget.data.orderID));
                                  },
                                  child: Column(
                                    children: List.generate(
                                        tempList.length,
                                            (position) => Container(
                                          color: Colors.white,
                                          padding: EdgeInsets.only(
                                              left: 10, right: 10),
                                          child: IntrinsicHeight(
                                            child: Row(
                                              children: [
                                                //这个Container描绘左侧的线和圆点
                                                Container(
                                                  margin: EdgeInsets
                                                      .only(
                                                      left: 10),
                                                  width: 20,
                                                  //需要根据文本内容调整高度，不然文本太长会撑开Container，导致线会断开
//                        height: getHeight(recordList[position].stateName),
                                                  child: Column(
                                                    //中心对齐，
                                                    mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .center,
                                                    children: [
                                                      Expanded(
                                                          flex: 1,
                                                          child:
                                                          Container(
                                                            //第一个item圆点上方的线就不显示了
                                                            width: position ==
                                                                0
                                                                ? 0
                                                                : 1,
                                                            color: Colors
                                                                .grey
                                                                .shade300,
                                                          )),
                                                      //第一个item显示稍大一点的绿色圆点
                                                      position == 0
                                                          ? Stack(
                                                        //圆心对齐（也就是中心对齐）
                                                        alignment:
                                                        Alignment.center,
                                                        children: <
                                                            Widget>[
                                                          //为了实现类似阴影的圆点
                                                          Container(
                                                            height: 16,
                                                            width: 16,
                                                            decoration: BoxDecoration(
                                                              color: Colors.red.shade200,
                                                              borderRadius: BorderRadius.all(Radius.circular(10)),
                                                            ),
                                                          ),
                                                          Container(
                                                            height: 10,
                                                            width: 10,
                                                            decoration: BoxDecoration(
                                                              color: Colors.red,
                                                              borderRadius: BorderRadius.all(Radius.circular(7)),
                                                            ),
                                                          ),
                                                        ],
                                                      )
                                                          : Container(
                                                        height:
                                                        10,
                                                        width:
                                                        10,
                                                        decoration:
                                                        BoxDecoration(
                                                          color:
                                                          Colors.grey.shade300,
                                                          borderRadius:
                                                          BorderRadius.all(Radius.circular(5)),
                                                        ),
                                                      ),
                                                      Expanded(
                                                          flex: 1,
                                                          child:
                                                          Container(
                                                            width: position ==
                                                                tempList.length - 1
                                                                ? 0
                                                                : 1,
                                                            color: Colors
                                                                .grey
                                                                .shade300,
                                                          )),
                                                    ],
                                                  ),
                                                ),
                                                Expanded(
                                                  child: Padding(
                                                    padding:
                                                    EdgeInsets
                                                        .fromLTRB(
                                                        20,
                                                        5,
                                                        20,
                                                        5),
                                                    child: Text(
                                                      '${tempList[position].createDate.replaceAll('T', ' ')}    ${tempList[position].content}',
                                                      style:
                                                      TextStyle(
                                                        //第一个item字体颜色为绿色+稍微加粗
                                                        color: position ==
                                                            0
                                                            ? Colors
                                                            .red
                                                            : Colors
                                                            .black,
                                                        fontWeight: position ==
                                                            0
                                                            ? FontWeight
                                                            .w600
                                                            : null,
                                                      ),
                                                      overflow:
                                                      TextOverflow
                                                          .ellipsis,
                                                      maxLines: 1,
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        )).toList(),
                                  ),
                                ),
                                InkWell(
                                    child: Padding(
                                      padding: EdgeInsets.all(10),
                                      child: Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '查看更多',
                                            style:
                                            TextStyle(fontSize: 12),
                                          ),
                                          Image.asset(
                                            'assets/right.png',
                                            width: 15,
                                            height: 15,
                                          )
                                        ],
                                      ),
                                    ),
                                    onTap: () {
                                      push(
                                          context,
                                          OrderRecordPage(
                                              widget.data.orderID));
                                    })
                              ],
                            ))
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(0, 5, 20, 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Visibility(
                      visible: widget.data.state==1,
                      child: ElevatedButton(
                          onPressed: () async {
                            var result=await push(context,FeeAuditDetailPage(widget.data));
                            if(result!=null){
                              getFeeInfo();
                            }
                          },
                          child: Text('审核')),
                    )
                  ],
                ))
          ],
        ):Center(child: CircularProgressIndicator())
    );
  }
  Widget buildImageItem(int index) {
    var scWidth = MediaQuery.of(context).size.width;
    var wh = (scWidth - 40) / 5;
    return GestureDetector(
        onTap: () {},
        behavior: HitTestBehavior.opaque,
        child: container(index, wh));
  }

  Widget container(int index, double wh) {
    if (feeDetailEntity.imgs[index] == null) {
      return Container(
          height: wh, child: Center(child: CircularProgressIndicator()));
    } else {
      return GestureDetector(
          onTap: (){
            //FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
            Navigator.of(context).push(FadeRoute(
                page: PhotoViewGalleryScreen(
                  images: feeDetailEntity.imgs, //传入图片list
                  index: index, //传入当前点击的图片的index
                  heroTag: '', //传入当前点击的图片的hero tag （可选）
                )));
          },
          child: Container(
              child: Image(
                image: CachedNetworkImageProvider(feeDetailEntity.imgs[index]),
                width: wh,
                height: wh,
                fit: BoxFit.fill,
              )));
    }
  }
}
